<template>
    <view class="page-home position-r">
        <map class="map" show-location :latitude="latitude" :longitude="longitude" :markers="covers" @tap="tap" @markertap="markertap" ></map>


        <view class="adv position-a full-w pd-v-24 box" v-if="banners.length"> 
            <!-- <image class="border8 over-h" src="@/static/adv.png" style="width:100%;" mode="widthFix" /> -->
             <swiper  :style="{ height: swiperHeight }" circular indicator-dots="true" :autoplay="true" interval="2000" duration="500">
                <swiper-item v-for="(item,index) in banners" :key="index+'index'" @click="bannerClick">
                    <image class="border8 over-h adv" :src="item.image" style="width:100%;" mode="widthFix"  @load="advLoad(index, $event)" />
                </swiper-item>
             </swiper>
        </view>

        <view class="charging flex flex-ver flex-center flex-j-center position-a" v-if="isCharging">
            <image class="img"  src="@/static/charging.png" mode="widthFix" />
        </view>
        
        <view class="cover bg-white" v-if="store?.common?.advShow">
          <image class="full-w full-h" @load="imgLoad" @click="bannerClick" src="@/static/1.jpg" mode="aspectFill"></image>
          <view class="position-a cover-tag">
                <u-tag @click="closeCover" text="跳过" shape="circle" bgColor="#000" color="#fff" size="medium"> </u-tag>
            </view>
        </view>

        <view class="active-shop position-a bg-white  border16 shadow pd-v-32 pd-h-40" @click="goDetail" v-if="activeShopShow">
            <view class="flex flex-center">
                <view class="flex-1 w0 line1 font32 bold lh-48">{{activeShop.name}}</view>
                <view class="flex flex-center">
                    <u-icon name="map-fill" color="#35BE65" size="16"></u-icon>
                    <text class="txt-center  font24 lh-24 color-note mr-l-8">{{activeShop?.distance}}</text>
                </view>
            </view>
            <view class="flex flex-center mr-t-30">
                <view class="flex-1 color-main flex flex-end">
                    <view class="price font52 lh-48 color-main flex flex-end">
                        <view class="font32 lh-32 color-main">
                            ￥
                        </view>
                          {{activeShop.chargeFee}}
                    </view>
                    <view class="flex-1 unit font28 lh-28 color-main">
                        /度+服务费
                    </view>
                </view>
                <u-button type="primary" shape="circle" color="#35BE65" :customStyle="{width:'170rpx',height:'60rpx',padding:'14rpx 12rpx',fontSize:'24rpx'}" >
                    <image src="@/static/battery.png" style="width:26rpx;" mode="widthFix" class="mr-r-6"></image>
                    {{activeShop.socketFreeCount+'/'+activeShop.socketTotalCount}}
                </u-button>
                 
            </view>

            <!-- <view class="pd-v-52 mr-t-20">
                <u-button type="primary" shape="circle"  text="去充电" color="#35BE65"></u-button>
            </view> -->
            
        </view>
        
        
        <tab></tab>
          
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { onLoad, onShow,onPullDownRefresh } from '@dcloudio/uni-app';
import { bannerList, storeAllList, settingGetInfo } from '@/api/index/index.js'

import tab from '@/components/tab.vue'
import { fileUrl } from '@/utils/index.js'
import { judgeIsStartCharging } from '@/api/user'
// #ifdef MP-WEIXIN
const amapFile  = require('../../static/amap-wx.130.js');
// #endif

// const QQMapWX = require('../../static/qqmap-wx-jssdk.js');
const store = useStore();
const includePoints = ref([])
const scale = ref(12)

onPullDownRefresh(() => {
    uni.stopPullDownRefresh()
})
 
onShow(() => {
    
    store.user.SET_USERINFO1('')
    store.user.SET_TOKEN1('') 
    uni.removeStorageSync('token1')
    uni.removeStorageSync('userInfo1')
    
    if(store?.user.token) {
        getJudgeIsStartCharging()
    } else {
        if(url.value) {
            let equipmentReg = /equipment\/([^\/]+)/
            let socketReg = /socket\/([^\/]+)/
            let equipmentMatch = url.value.match(equipmentReg)
            let socketMatch = url.value.match(socketReg)
            if(equipmentMatch && equipmentMatch[1] &&  socketMatch && socketMatch[1]) {
                if(store?.user.token) {
                    url.value = ''
                    uni.navigateTo({
                        url: '/sub_user/pages/chargePayment/chargePayment?deviceNumber='+equipmentMatch[1]+'&port='+socketMatch[1]
                    })
                } else {
                    url.value = ''
                    uni.navigateTo({
                        url: '/sub_user/pages/login/login'
                    })
                }
            } else if(equipmentMatch && equipmentMatch[1] && !socketMatch) {
                if(store?.user.token) {
                    url.value = ''
                    uni.navigateTo({
                        url: '/sub_user/pages/chargeSelect/chargeSelect?deviceNumber='+equipmentMatch[1]
                    })
                } else {
                    url.value = ''
                    uni.navigateTo({
                        url: '/sub_user/pages/login/login'
                    })
                }
            }
        }
    }

    getBannerList()
    // if(uni.getStorageSync('token')) {
    //     store.user.SET_TOKEN(uni.getStorageSync('token'))
    // }
    // if(uni.getStorageSync('userInfo')) {
    //     store.user.SET_USERINFO(uni.getStorageSync('userInfo'))
    // }
})

const covers = ref([])


const latitude = ref(null);
const longitude = ref(null);
const banners = ref([])
const currentLocation = ref({})
const isCharging = ref(false);
const url = ref('')
const swiperHeight = ref('300rpx');
const imageHeights = ref([]); // 存储图片的高度
const activeShop = ref({});
const activeShopShow = ref(false);
const shopList = ref([])
const isClickMap = ref(false);
const timer = ref(null);

onLoad((options) => {

    getSettingGetInfo()
    
    if(options && options.q) {
        url.value = options.q;
        
    }

    store.user.SET_USERINFO1('')
    store.user.SET_TOKEN1('')
    uni.removeStorageSync('token1')
    uni.removeStorageSync('userInfo1')
    store.user.SET_USERINFO2('')
    store.user.SET_TOKEN2('')
    uni.removeStorageSync('token2')
    uni.removeStorageSync('userInfo2')
    uni.getLocation({
        type:'gcj02',
        isHighAccuracy:true,
		geocode:true,
        success: (res) => {
			console.log(1)
            console.log(res,'resssssss')
            longitude.value = res.longitude
            latitude.value = res.latitude
            
			// #ifdef MP-WEIXIN
            var myAmapFun = new amapFile.AMapWX({ key: '6fedb410f239b45906834cd2ac88a3f9' });

            myAmapFun.getRegeo({
                success: function (data) { 
                    //成功回调
                    console.log(data)
                    // includePoints.value = [{
                    //     longitude: res.longitude,
                    //     latitude: res.latitude
                    // }]
                    
                    currentLocation.value = {
                        currentLocation:data[0].longitude+','+data[0].latitude,
                        province:data[0].regeocodeData.addressComponent.province,
                        city:data[0].regeocodeData.addressComponent.city,
                        // district:data[0].regeocodeData.addressComponent.district
                    };
                    getStoreAllList()
                },
                fail: function (info) {
                    //失败回调
                    console.log(info)
                }
            })
			// #endif
			
			 
            // const qqmapsdk = new QQMapWX({
            //     key: 'NZFBZ-U7T6R-EW5WI-WFRUF-I66JS-ZRFG4' // 必填
            // });
            
            // // console.log(res);
            // qqmapsdk.reverseGeocoder({
			// 	  //Object格式
            //     location: {
            //         latitude: res.latitude,
            //         longitude: res.longitude
            //     }, 
            //     success: function(geoRes) {//成功后的回调
                    
            //         currentLocation.value = {
            //             currentLocation:res.longitude+','+res.latitude,
            //             province:geoRes.result.address_component.province,
            //             city:geoRes.result.address_component.city,
            //             // district:geoRes.result.address_component.district
            //         };
            //         getStoreAllList()
            //     },
            //     fail: function(error) {
            //         console.log(error,'error');
            //     },
            //     complete: function(res) {
            //     //console.log(res);
            //     }
            // });
            
        },
        fail: (res) => {
            console.log('失败！！', res);
        }
    })

})

const getSettingGetInfo = () => {
    settingGetInfo().then(res => {
        if(res.code == 200) {
          store.common.SET_PLATFORMINFO(res.data)
        }
    })
}

const advLoad = (index,event) => {
    console.log(index,event)
    const { width, height } = event.detail;
    let actualHeight = height / (width / 750);
        imageHeights.value[index] = actualHeight;
    if (index === 0) {
        swiperHeight.value = actualHeight + 'rpx';
    }
}

const imgLoad = () => {
  timer.value = setTimeout(() => {
      store.common.SET_ADVSHOW(false)
  }, 10000);
}


const closeCover = () => {
    clearTimeout(timer.value);
    store.common.SET_ADVSHOW(false)
}

const getStoreAllList = () => {
    console.log(JSON.parse(JSON.stringify(currentLocation.value)))
    storeAllList(currentLocation.value).then(res => {
        if(res.code == 200) {
            shopList.value = res.data
            let coversList = []
            res.data.forEach(item => {
                let coversItem = {
                    latitude: item.location.split(',')[1],
                    longitude: item.location.split(',')[0],
                    id:item.id,
                    width:31,
                    height:31,
                    iconPath: '/static/light.png',
                    callout:{
                        content:item.socketFreeCount+'/'+item.socketTotalCount,
                        fontSize:14,
                        bgColor:'#ffffff',
                        padding:8,
                        color:'#333',
                        borderRadius:10,
                        display:'ALWAYS'
                    },
                }

                coversList.push(coversItem)
            });

            covers.value = coversList
            
        }

    })
}


const getBannerList = () => {
    bannerList().then(res => {
        if (res.code == 200) {
            res.rows.forEach(item => {
                item.image = fileUrl(item.image);
            })

            banners.value = res.rows;
        }
    })
}

const bannerClick = (e) => {
// #ifndef MP-WEIXIN
    uni.makePhoneCall({
        phoneNumber: store?.common?.platformInfo?.platformCustomerServicePhone
    });
// #endif

// #ifdef MP-WEIXIN
    wx.openOfficialAccountArticle({
        url:'https://mp.weixin.qq.com/s/nafApeayNAyZccnejlbKmg'
    })
// #endif
}





const markertap = (e) => {
    console.log(e)
    isClickMap.value = true;
    let id = e.detail.markerId

    let shopItem = shopList.value.find(item => item.id == id)

    if(shopItem) {
        activeShop.value = shopItem
        activeShop.value.distance = getDistance(shopItem.location)
        activeShopShow.value = true
        setTimeout(() => {
            isClickMap.value = false;
        }, 500);
        
    }
}


const goDetail = (item) => { 
    if(!store?.user?.token) {
        uni.navigateTo({
            url: '/sub_user/pages/login/login'
        })
        return;
    }
    uni.navigateTo({
        url: '/sub_user/pages/detail/detail?id='+activeShop.value.id
    })
}


const getJudgeIsStartCharging = () => {
    judgeIsStartCharging().then(res => {
        if(res.code == 200) {
            isCharging.value = !res.data;
            if(url.value) {
                let equipmentReg = /equipment\/([^\/]+)/
                let socketReg = /socket\/([^\/]+)/
                let equipmentMatch = url.value.match(equipmentReg)
                let socketMatch = url.value.match(socketReg)
                if(equipmentMatch && equipmentMatch[1] &&  socketMatch && socketMatch[1]) {
                    if(store?.user.token) {
                        url.value = ''
                        uni.navigateTo({
                            url: '/sub_user/pages/chargePayment/chargePayment?deviceNumber='+equipmentMatch[1]+'&port='+socketMatch[1]
                        })
                    } else {
                        url.value = ''
                        uni.navigateTo({
                            url: '/sub_user/pages/login/login'
                        })
                    }
                } else if(equipmentMatch && equipmentMatch[1] && !socketMatch) {
                    if(store?.user.token) {
                        url.value = ''
                        uni.navigateTo({
                            url: '/sub_user/pages/chargeSelect/chargeSelect?deviceNumber='+equipmentMatch[1]
                        })
                    } else {
                        url.value = ''
                        uni.navigateTo({
                            url: '/sub_user/pages/login/login'
                        })
                    }
                }
            }
        }
    }).catch(err => {
        console.log(err,'err')
        if(url.value) {
            url.value = ''
            uni.navigateTo({
                url: '/sub_user/pages/login/login'
            })
        }
    })
}

const tap = (e) => {
    if(isClickMap.value) {
        return;
    } else {
        isClickMap.value = false;
        activeShop.value = {}
        activeShopShow.value = false
    }
}

const getDistance = (location) => {
    if(!location) {
        return ''
    }
    let point1 = {
        latitude: latitude.value,
        longitude: longitude.value
    }

    let point2 = {
        latitude: location.split(',')[1],
        longitude: location.split(',')[0]
    }
    let R = 6371000; // 地球平均半径，单位：米
    let lat1 = point1.latitude * Math.PI / 180;
    let lat2 = point2.latitude * Math.PI / 180;
    let lon1 = point1.longitude * Math.PI / 180;
    let lon2 = point2.longitude * Math.PI / 180;
    let a = Math.sin((lat2 - lat1) / 2) * Math.sin((lat2 - lat1) / 2) +
            Math.cos(lat1) * Math.cos(lat2) * Math.sin((lon2 - lon1) / 2) * Math.sin((lon2 - lon1) / 2);
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let d = R * c; // 初始计算得到的距离，单位：米
 
    if (d >= 1000) {
        // 如果距离大于等于1000米（即1千米），则换算为千米并保留两位小数
        return (d / 1000).toFixed(2) + "km";
    } else {
        return d.toFixed(2) + "m";
    }
}
</script>

<style lang="scss">
.page-home {
    overflow: hidden;

    .w {
        width:0;
    }

    .active-shop {
        width:600rpx;
        left:50%;
        bottom:300rpx;
        transform: translateX(-50%);
    }
    .cover {
        width: 100vw;
        height: 100vh;
        position:fixed;
        left:0;
        top:0;
        z-index: 99999999999999;

        .cover-tag {
            bottom:10vh;
            right:10vw;

            .u-tag {
                border:1px solid rgba(255,255,255,0.7) !important;
                width:80rpx;
                justify-content: center;
            }
        }
    }
    .map {
        width: 100vw;
        height: 100vh;
    }

    .adv {
        top:200rpx;
        left:0;
        
    }

    .charging {
        right:16rpx;
        bottom: 360rpx;
        .img {
            width: 136rpx;
        }

        .text {
            color: #fff;
            background: #2A88FB;
            box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.3);
            padding:4rpx 24rpx;
            border-radius:50rpx;
        }
    }
}
</style>
